#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>

int get_usrname(uid_t uid)
{
	struct passwd *pwd=getpwuid(uid);
	if(NULL==pwd)
	{
		printf("getpwuid failed\n");
		return -1;
	}
	printf("%s",pwd->pw_name);
	return 0;
}
int get_grpname(gid_t gid)
{
	struct group*grp = getgrgid(gid);
	if(NULL ==grp)
	{
		printf( "getgrgid failed\n" );
		return -1;
	}
	printf( "%s" , grp->gr_name);
	return 0;
}
void mode(mode_t a)
{
	char s[3]={'r','w','x'};
	int index=0;
	for(int i=8;i>=0;i--)
	{
		if(a&1<<i)
		{
			printf("%c",s[(i+1)%3]);
		}
		else
		{
			printf("-");
		}
	}
	//printf("\n");
}
int get_fileType(mode_t m)
{
	switch (m & S_IFMT) 
	{
	case S_IFBLK:
		printf("b");           
		break;
	case S_IFCHR:  
		printf("c");        
		break;
	case S_IFDIR:  
		printf("d");               
		break;
	case S_IFIFO:  
		printf("p");               
		break;
	case S_IFLNK:  
		printf("l");                 
		break;
	case S_IFREG:  
		printf("-");            
		break;
	case S_IFSOCK: 
		printf("s");                  
		break;
	default:
		printf("?");                
		break;
	}

}
int timeset(__time_t *t)
{
	struct tm *info=NULL;
	info=localtime(t);
	fprintf(stdout,"%d月  %02d %02d:%02d", \
			info->tm_mon+1, info->tm_mday,\
			info->tm_hour, info->tm_min);
	fflush(stdout);
	return 0;
}

int main(int argc, const char *argv[])
{
	DIR* dp =opendir(argv[1]);
	if(NULL ==dp)
	{
		perror( "opendir" );
		return -1;
	}
	struct dirent *rp = NULL;
	while(1)
	{
		rp = readdir(dp);
		if(NULL ==rp)
		{
			if(0 == errno)//没有更新错误码，目录被读取到结尾
			{
				//printf("目录读取完毕\n" );
				break;
			}
			else
			{
				perror( "readdir" );
				return-1;
			}
		}
		if(rp->d_name[0]=='.')
		{
			continue;
		}
		struct stat buf;		
		char str[100];
		strcpy(str,argv[1]);
		strcat(str,rp->d_name);
		if(stat(str,&buf)<0)
		{
			perror("stat");
			return -1;
		}
		//文件类型以及权限
		get_fileType(buf.st_mode);
		mode(buf.st_mode);
		printf(" ");

		//硬链接数
		printf("%ld ", buf.st_nlink);

		//文件所属用户
		get_usrname(buf.st_uid);
		printf(" ");

		//文件所属组用户
		get_grpname(buf.st_gid);
		printf(" ");

		//文件大小
		printf( "%6ld ", buf.st_size);

		//文件创建日期
		timeset(&buf.st_mtime);	
		printf(" ");
		printf("%s\n",rp->d_name);
	}
	closedir(dp);
	return 0;
}

